import Cls from 'classnames';
import pageStyles from '@/common/pageLayout.less';
import { useEffect, useMemo, useState } from 'react';
import { connect } from 'umi';
import { Card, Table, Divider, Button, Spin, message, Space } from 'antd';
import { SyncTableColumns } from '../mconfig';
import { history } from 'umi';
import { getKeyRouter, getPosIDs, getTenantID, getUserID, tooltipLength } from '@/utils';
import { AuditModal } from './AuditModal';
import { useNeedUpdate } from '../common/useNeedUpdate';
import { useNeedUpdateReducer } from '../common/NeedReducer';
import { SyncPlanModal } from './SyncPlanModal';
import { WorkflowCheckModal, WorkflowChedkRecord, WorkflowHndTaskBtn } from '@/components/WorkflowCommonCopy';
import UpdateNeedMaterialDetail from './UpdateNeedMaterialDetail';
import { JZLZ_STATE, KCBSH_STATE, SHZ_STATE, XQBZ_STATE, ZRBGH_STATE, purchaseNeedCategory, purchaseNeedController } from '../common/Format';
import '../common/style.less';
import { BZZ_CHECKSTATE, SHTH_CHECKSTATE, closeCurrent } from '../../Acommon';
import { ILoadMapTypeAll } from '@/common';

/**
 * 结果录入的页面&&审核物料列表的页面
 * */
const DetailsView = ({ curRes, locationProps }: Record<string, any>) => {
  /** 结构路由传参 */
  const {
    state: { info },
  } = locationProps;

  /** reducer */
  const { dispatch, materialList } = useNeedUpdateReducer();

  /** 样式类名 */
  const prefixCls = 'plan-detailtabel-';

  /** 随机id */
  const [pageRouterDomID, _setPageRouterDomID] = useState<string>(`needUpdateView-imageBox-${getKeyRouter()}`);

  /** 结构自定义hooks */
  const { change, needInfo, isShowState, loading } = useNeedUpdate({ locationProps, materialList, dispatch });

  const { reloadInfoFunc, fetchFindNeed } = change;

  useEffect(() => {
    let { info } = locationProps?.state;
    if (info?.id) fetchFindNeed({ id: info?.id });
  }, [locationProps?.state]);

  /** 是否显示计划下达弹窗 */
  const [isShowSync, setIsShowSync] = useState<Record<string, any>>({
    isShow: false,
    resObj: {},
  });

  /** 是否显示物料详情抽屉 */
  const [isShowDrawer, setIsShowDrawer] = useState<Record<string, any>>({
    isShow: false,
    resId: null,
  });

  /** 是否显示审核弹窗 */
  const [isShowAudit, setIsShowAudit] = useState<Record<string, any>>({
    isShow: false,
    selectId: '',
    type: '',
    planInfo: {},
    way: '',
  });

  /** 是否显示撤销按钮 */
  const [isRevoke, setIsRevoke] = useState<Record<string, any> | null>(null);

  /** 工作流提交弹窗是否显示 */
  const [isShowWorkflowCheck, setIsShowWorkflowCheck] = useState<Record<string, any>>({});

  /** 多选列表id */
  const [selectKeys, setSelectKeys] = useState<any[]>([]);

  /** 方法集合 */
  const operateFuns = {
    onAudit: (record: Record<string, any>, value: string) => {
      //onAudit(点击审核事件)
      setIsShowAudit({
        isShow: true,
        selectId: record?.id,
        type: 'radio',
        planInfo: needInfo,
        way: value,
      });
    },
    onView: (id: string) => {
      //onVie(点击物料标题)
      setIsShowDrawer({
        isShow: true,
        resId: id,
      });
    },
  };

  /** 批量审核方法 */
  const batchAudit = () => {
    if (selectKeys?.length >= 1) {
      setIsShowAudit({
        isShow: true,
        selectId: selectKeys?.toString(),
        type: 'checkBox',
        planInfo: needInfo,
        way: '',
      });
    } else {
      message.warning('请选择物料！');
    }
  };

  /** 表格多选事件 */
  const onSelectChange = (key: any[], record: any[]) => {
    setSelectKeys(key);
  };

  /** 已审核，待审核，总数 */
  const NumGatherMemo = useMemo(() => {
    let resObj = {
      yiNum: 0,
      daiNum: 0,
      allNum: materialList?.length || 0,
    };

    let num = 0;
    materialList?.forEach((item: Record<string, any>) => {
      if (!item?.checkState) {
        num += 1;
      }
    });
    resObj.daiNum = num;
    resObj.yiNum = resObj?.allNum - num;
    return resObj;
  }, [materialList, needInfo]);

  useEffect(() => {
    /** 当state为需求编制，checkState为退回 */
    if (needInfo?.state && needInfo?.state == XQBZ_STATE() && needInfo?.checkState == SHTH_CHECKSTATE()) {
      history.push({
        // 新增编辑页
        pathname: `/purchaseNeedController/edit/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          info: needInfo,
          delRouterName: history.location.pathname, //必传,要删除的路由名称
        },
      });
    } else {
      if (needInfo?.state && (needInfo?.state == SHZ_STATE() || needInfo?.state == KCBSH_STATE())) {
        history.push({
          // 新增编辑页
          pathname: `/purchaseNeedController/getPurchaseNeedByID/{id}/{currentUserID}/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            info: needInfo,
            delRouterName: history.location.pathname, //必传,要删除的路由名称
          },
        });
      }
    }
  }, [needInfo?.state, needInfo?.checkState, curRes]);

  /** 是否可以办理流程 */
  const nodesFlowListMemo = useMemo(() => {
    const taskHandInfo: Record<string, any> = needInfo?.paramObject?.[purchaseNeedCategory()];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      return taskHandInfo?.mactivitiTaskList?.[0];
    } else {
      return false;
    }
  }, [needInfo?.paramObject]);

  /** 是否显示【批量审核button】和多选框【checkbox】 */
  const isShowAuditMemo = useMemo(() => {
    return needInfo?.state && needInfo?.state == ZRBGH_STATE() && needInfo?.checkState == BZZ_CHECKSTATE() && nodesFlowListMemo;
  }, [needInfo?.state, needInfo?.checkState, nodesFlowListMemo]);

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100%',
        overflow: 'hidden',
      }}
    >
      <Card
        id={pageRouterDomID}
        title={'需求状态：主任办公会审议'}
        bodyStyle={{
          display: 'flex',
          flexDirection: 'column',
          height: '100%',
          width: '100%',
          overflow: 'hidden',
        }}
        className={Cls(pageStyles['page-view-cardView'], prefixCls + 'rootBox', 'needUpdateView-imageBox')}
        actions={
          locationProps?.state?.returnPathName
            ? [
                <div>
                  <Space>
                    <Button danger onClick={() => closeCurrent(locationProps?.state?.returnPathName)}>
                      关闭
                    </Button>
                  </Space>
                </div>,
              ]
            : undefined
        }
        extra={[
          // <div>
          //   <Space>
          //     <WorkflowHndTaskBtn
          //       flowDetailInfo={needInfo}
          //       requestController={purchaseNeedController}
          //       reloadCallback={reloadInfoFunc}
          //       isAloneSubmit={needInfo?.state && nodesFlowListMemo && needInfo?.state == ZRBGH_STATE() && needInfo?.checkState == BZZ_CHECKSTATE()}
          //       clickBeforeFun={() => {
          //         return new Promise((resolve) => {
          //           if (NumGatherMemo?.allNum == NumGatherMemo?.yiNum) {
          //             resolve(true);
          //           } else {
          //             message.warn(`提示：还有标的未审核 , 待审核数量为: ${NumGatherMemo?.daiNum}`);
          //           }
          //         });
          //       }}
          //       flowBusinessType={purchaseNeedCategory()}
          //     />
          //     {curRes['/purchaseNeedController/invalid'] &&
          //       needInfo?.id &&
          //       needInfo?.applyerID == getUserID() &&
          //       needInfo?.applyPositionID == getPosIDs() &&
          //       (needInfo?.state == SHZ_STATE() || needInfo?.state == JZLZ_STATE() || needInfo?.state == ZRBGH_STATE()) && (
          //         <Button
          //           type="primary"
          //           danger
          //           // icon={<RollbackOutlined />}
          //           onClick={() => setIsRevoke({ isShow: true, resObj: needInfo })}
          //         >
          //           撤销
          //         </Button>
          //       )}
          //   </Space>
          // </div>,
          <WorkflowHndTaskBtn
            flowDetailInfo={needInfo}
            requestController={purchaseNeedController}
            reloadCallback={reloadInfoFunc}
            isAloneSubmit={needInfo?.state && nodesFlowListMemo && needInfo?.state == ZRBGH_STATE() && needInfo?.checkState == BZZ_CHECKSTATE()}
            clickBeforeFun={() => {
              return new Promise((resolve) => {
                if (NumGatherMemo?.allNum == NumGatherMemo?.yiNum) {
                  resolve(true);
                } else {
                  message.warn(`提示：还有标的未审核 , 待审核数量为: ${NumGatherMemo?.daiNum}`);
                }
              });
            }}
            flowBusinessType={purchaseNeedCategory()}
            applyHeader={'apply'}
            revokeRequestUrl={'/purchaseNeedController/invalid'}
            revokeRequestState={`${getTenantID()}${ILoadMapTypeAll.NEED_STATE}`}
            isShowRevokeStateList={[SHZ_STATE(), JZLZ_STATE(), ZRBGH_STATE()]}
            revokeTitle={needInfo?.needName}
            revokeSuccessCallback={() => {
              history.push({
                // 新增编辑页
                pathname: `/purchaseNeedController/edit/:${getKeyRouter()}${getKeyRouter()}`,
                state: {
                  info: needInfo,
                  isView: false,
                  delRouterName: history.location.pathname,
                  returnPathName: locationProps?.state?.returnPathName,
                },
              });
            }}
          />,
        ]}
      >
        <Spin spinning={loading}>
          <div className={prefixCls + 'rootBox-textTitle'}>
            <Divider style={{ fontSize: '1.3rem' }}>{tooltipLength(info?.needName, 50)}</Divider>
          </div>
          {isShowAuditMemo && curRes?.['/purchaseNeedMaterialController/check'] && (
            <div style={{ display: 'flex', justifyContent: 'space-between', margin: '0.2rem 1rem' }}>
              <div style={{ display: 'flex' }}>
                <Button
                  type="primary"
                  // icon={<MenuUnfoldOutlined />}
                  style={{}}
                  onClick={batchAudit}
                >
                  批量操作
                </Button>
                <div style={{ lineHeight: '35px', marginLeft: '10px' }}>
                  已选择&nbsp;
                  <span style={{ color: '#1677ff', fontWeight: '700' }}>{selectKeys?.length}</span>
                  &nbsp;个物料
                </div>
              </div>
              <div style={{ display: 'flex', lineHeight: '35px' }}>
                <div>
                  已审核&nbsp;
                  <span style={{ color: '#1677ff', fontWeight: '700' }}>{NumGatherMemo?.yiNum}</span>
                  &nbsp;个物料
                </div>
                <div style={{ marginLeft: '10px' }}>/</div>
                <div style={{ marginLeft: '10px' }}>
                  待审核&nbsp;
                  <span style={{ color: '#1677ff', fontWeight: '700' }}>{NumGatherMemo?.daiNum}</span>
                  &nbsp;个物料
                </div>
              </div>
            </div>
          )}
          <div className={Cls('list-table', prefixCls + 'rootBox-materilTable')}>
            <Table
              bordered
              size="small"
              scroll={{ x: 1200, y: 1200 }}
              dataSource={materialList || []}
              columns={SyncTableColumns(curRes, operateFuns, needInfo?.state, needInfo, nodesFlowListMemo) as any}
              rowKey={'id'}
              pagination={false}
              rowSelection={
                isShowAuditMemo
                  ? {
                      // 表格多选
                      type: 'checkbox',
                      onChange: onSelectChange,
                      selectedRowKeys: selectKeys,
                      getCheckboxProps: (record) => ({
                        disabled: Number(record?.expectSum) < 1000000,
                      }),
                    }
                  : undefined
              }
              onRow={(record) => {
                return {
                  onClick: () => {
                    if (record?.checkState !== 0) return;
                    const selectInfo: any = selectKeys?.find((item: any) => item == record?.id);
                    if (selectInfo == undefined) {
                      setSelectKeys([...selectKeys, record?.id]);
                    } else {
                      const Index = selectKeys?.indexOf(selectInfo);
                      let newarr = [...selectKeys];
                      newarr?.splice(Index, 1);
                      setSelectKeys(newarr);
                    }
                  },
                };
              }}
            />
          </div>
        </Spin>
        <UpdateNeedMaterialDetail
          isShowDetail={isShowDrawer?.isShow}
          materialId={isShowDrawer?.resId}
          pageRouterDomID={pageRouterDomID}
          onClose={() => {
            setIsShowDrawer({
              isShow: false,
              resId: null,
            });
          }}
        />
      </Card>

      {/* 工作流审核记录展示 */}
      <WorkflowChedkRecord
        curRes={curRes}
        dataDetailInfo={needInfo}
        flowBusinessType={purchaseNeedCategory()}
        requestController={purchaseNeedController}
        reloadPageCallback={() => {}} // 刷新方法-详情方法
        revokeStateID={XQBZ_STATE()}
        allBtnFuncQuqry={isShowState?.workflowPowerAllBtn}
        tabPaneHeight={0.35}
        changeCollapse={() => {}}
        cancelStateId={''}
        // isSyncArchive={true}
      />

      {/* 工作流审批弹窗 */}
      {isShowWorkflowCheck?.isShow && (
        <WorkflowCheckModal
          detailInfoObj={needInfo?.paramObject?.[purchaseNeedCategory()]?.mactivitiTaskList?.[0]}
          flowBusinessType={purchaseNeedCategory()}
          requestController={purchaseNeedController}
          clickBtnText={isShowWorkflowCheck?.resObj}
          reloadCallback={reloadInfoFunc}
          onClose={() => {
            setIsShowWorkflowCheck({});
          }}
        />
      )}

      {/* 业务审核物料弹窗 */}
      {isShowAudit?.isShow && (
        <AuditModal
          isShowAudit={isShowAudit}
          onClose={() => setIsShowAudit({})}
          getPlanInfo={() => {
            reloadInfoFunc();
            setSelectKeys([]);
          }}
        />
      )}

      {/* 下达计划弹窗 */}
      {isShowSync?.isShow && <SyncPlanModal onClose={() => setIsShowSync({})} />}

      {/* 撤销弹窗 */}
      {/* {isRevoke?.isShow && (
        <RevokeModal
          resObj={needInfo}
          revokeRequestUrl={'/purchaseNeedController/invalid'}
          onClose={() => setIsRevoke(null)}
          reqBody={{ state: XQBZ_STATE() }}
          modalTip={
            <div style={{ color: '#000' }}>
              确认是否撤销【<span style={{ color: 'red' }}>{needInfo?.needName}</span>】的审核, 撤销后可重新提交！
            </div>
          }
          reloadRequest={() => {
            // 跳转新增编辑页
            history.push({
              pathname: `/purchaseNeedController/edit/:${getKeyRouter()}${getKeyRouter()}`,
              state: {
                info: needInfo,
                isView: false,
                delRouterName: history.location.pathname,
              },
            });
          }}
        />
      )} */}
    </div>
  );
};
export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(DetailsView);

/** 当state为主任办公会，checkstate为审核通过，并且没有计划id的绑定，则跳转新增编辑页面 */
// if (needInfo?.state == JHXD_STATE() && needInfo?.checkState == SHTG_CHECKSTATE()) {
//   if (!needInfo?.purchasePlan?.id) {
//     /** 计算通过的物料总价 */
//     let allExpectSum = 0;
//     needInfo?.purchaseNeedMaterials?.forEach((item) => {
//       if (item?.checkState == 1) {
//         allExpectSum += Number(item?.expectSum);
//       }
//     });

//     /** 调添加到计划的接口 */
//     let addPlanData = {
//       supplyWay: needInfo?.supplyWay,
//       supplyKind: needInfo?.supplyKind,
//       planName: needInfo?.needName?.replace('需求', '计划'), //数据进入计划管理，将后缀改成计划管理
//       planInfo: needInfo?.needInfo,
//       expectSum: allExpectSum,
//       state: '0',
//       // <<<========================================>>>
//       applyCompanyID: needInfo?.applyCompanyID,
//       applyCompanyName: needInfo?.applyCompanyName,
//       applyDepartmentID: needInfo?.applyDepartmentID,
//       applyDepartmentName: needInfo?.applyDepartmentName,
//       applyPositionID: needInfo?.applyPositionID,
//       applyPositionName: needInfo?.applyPositionName,
//       applyerID: needInfo?.applyerID,
//       applyerName: needInfo?.applyerName,
//       applyTime: needInfo?.applyTime,
//       ownCompanyID: needInfo?.ownCompanyID,
//       ownCompanyName: needInfo?.ownCompanyName,
//       ownDepartmentID: needInfo?.ownDepartmentID,
//       ownDepartmentName: needInfo?.ownDepartmentName,
//       ownPhone: needInfo?.ownPhone, // 联系电话
//       ownPositionID: needInfo?.ownPositionID,
//       ownPositionName: needInfo?.ownPositionName,
//       ownTime: needInfo?.ownTime,
//       ownerID: needInfo?.ownerID,
//       ownerName: needInfo?.ownerName, // 联系人
//       // <<<========================================>>>
//       mpurchaseNeeds: [{ id: needInfo?.id }],
//       purchaseNeedMaterials: needInfo?.purchaseNeedMaterials?.map((item) => {
//         return { id: item?.id };
//       }),
//     };
//     addPlanRun(addPlanData);
//     syncPDFtoOARunfun(needInfo);
//   }
// }

// /** 添加计划Callback */
// const addPlanCallback = (res: Record<string, any>) => {
//   if (res?.msgFlag) {
//     message?.success(res?.msg);
//     history.push({
//       // 新增编辑页
//       pathname: `/purchaseNeedController/getPurchaseNeedByID/{id}/{currentUserID}/:${getKeyRouter()}${getKeyRouter()}`,
//       state: {
//         info: needInfo,
//         delRouterName: history.location.pathname, //必传,要删除的路由名称
//       },
//     });
//   }
// };

// /** 同步审核记录给档案 */
// const { syncPDFtoOARun, syncPDFtoOALoading } = syncPDFtoOAServices((res) => { });

// const syncPDFtoOARunfun = (infoObj) => {
//   //需要调用同步接口
//   let mactivitiHisTaskInstList = infoObj?.paramObject?.[purchaseNeedCategory()]?.mactivitiHisProcinstList?.[0]?.mactivitiHisTaskInstList;
//   let resObj = { ...infoObj, paramObject: { mactivitiHisTaskInstList } };
//   syncPDFtoOARun(resObj);
// };

// /** 添加计划serivces */
// const { addPlanRun, addPlanLoading } = addPlanServices(addPlanCallback);
